APIKEY="BWN9pwIZx6aoSjhSeGEiFikd"
secret_key="1cNeE3iG2czhcRtjsLrEuOul100bxKNI"

import ischinese
import requests
import json,time,os
import pandas as pd

def get_access_token():
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+APIKEY+"&client_secret="+secret_key
    print(url)   
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")

def main(i,theme,name,token):
    print(i)
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token=" + token
    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                'content': '''If you are a chef at a five-star hotel, skilled in making creative dishes. Please make a dish of %s for 8 people that is suitable for American taste. Require that raw materials are easily available in supermarkets in the United States. Please list the ingredients and weight, preparation time, cooking time, cooking difficulty (1-5 levels, from simple to difficult), preparation method steps, nutritional ingredient list (including calories), dish characteristics, and 3-5 user comments. If there are any special precautions, please also list tips. The reply text must be output in full English, I don't understand Chinese characters. The output format should be:\n**[Dish Name]**\n\n**Ingredients and Weight**:\n\n[Ingredients and Weight]\n\n**Preparation Time**:\n\n[Preparation Time]\n\n**Preparation Time**:\n\n[Preparation Time]\n\n**Difficulty Level**:\n\n[Difficulty Level]\n\n**Preparation Method Steps**:\n\n[Preparation Method Steps]\n\n**Nutritional Information**:\n\n[Nutritional Information]\n\n**Dish Characteristics**:\n\n[Dish Characteristics]\n\n**User Comments**:\n\n[User Comments]\n\n**Special Precautions and Tips**:\n\n[Special Precautions and Tips]\n\n'''%(name)
                #"content": "If you are a chef at a five-star hotel, skilled in making creative dishes. Please make a dish of %s for 8 people that is suitable for American taste and themed around% s for your guests. Require that raw materials are easily available in supermarkets in the United States. Please list the ingredients and weight, preparation time, cooking time, cooking difficulty (1-5 levels, from simple to difficult), preparation method steps, nutritional ingredient list (including calories), dish characteristics, and 3-5 user comments. If there are any special precautions, please also list tips. The reply text must be output in full English (excluding Chinese characters)."%(name,theme)
            }
        ]
    })
    headers = {
        'Content-Type': 'application/json'
    }
    try:
        response = requests.request("POST", url, timeout=120, headers=headers, data=payload)
    except requests.exceptions.RequestException:
        return False
    if ischinese.judge(response.text): return False
    result = json.loads(response.text)
    if 'result' not in result: return False
    else:
        if max([ len(sent) for sent in result['result'].split("\n") ]) > 140: return False
        with open("./recipes/%d.md"%i,"w") as f:
            f.write(result['result']+"\n")
    print(response.text)
    return True
    
def main_google(i,name):
    apikey='AIzaSyD6tcwFInavhIbiniCsjsXiMWFNlpGgMOY'
    apikey='AIzaSyCgm7jn2bCWa437cgKkJP1_OhdS1cyknHk'
    apikey='AIzaSyAaVtOrZbUVkjeTvzvIw94__QGUlfmzGko'
    apikey='AIzaSyB7sK0vG1nRS8R9DK0QIG4F-p5Ncp2yhHc'
    apikey='AIzaSyBsGFRYULu1yRMA_H-gdU4OvGivvqJDClM'
    apikey='AIzaSyCOSDaM4seaORjDImLpa-tdxpr8YexLo5c'
    apikey='AIzaSyB3Jt8f4F1PZZR9dk6MViQ1O-xnfti90nU'
    url = f'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key={apikey}'
    headers = {'Content-Type': 'application/json'}
    data = {
        'contents': [
            {
                'parts': [
                    {
                        'text': '''If you are a chef at a five-star hotel, skilled in making creative dishes. Please make a dish of %s for 8 people that is suitable for American taste for your guests. Require that raw materials are easily available in supermarkets in the United States. Please list the ingredients and weight, preparation time, cooking time, cooking difficulty (1-5 levels, from simple to difficult), preparation method steps, nutritional ingredient list (including calories), dish characteristics, and 3-5 user comments. If there are any special precautions, please also list tips. The reply text must be output in full English, I don't understand Chinese characters. The output format should be:\n**[Dish Name]**\n\n**Ingredients and Weight**:\n\n[Ingredients and Weight]\n\n**Preparation Time**:\n\n[Preparation Time]\n\n**Preparation Time**:\n\n[Preparation Time]\n\n**Difficulty Level**:\n\n[Difficulty Level]\n\n**Preparation Method Steps**:\n\n[Preparation Method Steps]\n\n**Nutritional Information**:\n\n[Nutritional Information]\n\n**Dish Characteristics**:\n\n[Dish Characteristics]\n\n**User Comments**:\n\n[User Comments]\n\n**Special Precautions and Tips**:\n\n[Special Precautions and Tips]\n\n'''%(name)
                        }
                    ]
                }
            ]
        }
    try:
        response = requests.post(url, headers=headers, data=json.dumps(data))
    except requests.exceptions.RequestException:
        return False
    response_text = response.json()
    if 'candidates' not in response_text or 'content' not in response_text['candidates'][0] or 'parts' not in response_text['candidates'][0]['content'] or 'text' not in response_text['candidates'][0]['content']['parts'][0]: return False
    result = response_text['candidates'][0]['content']['parts'][0]['text']
    if ischinese.judge(result): return False
    else:
        with open("./recipes/%d.md"%i,"w") as f:
            f.write(result+"\n")
    print(result)
    print(i)
    return True

if __name__ == '__main__':
    #candidate = set([ item.split("\t")[0] for item in open("recipes.csv","r") ])
    #count_id = set([ item.split("/")[-1].split(".md")[0] for item in os.popen("ls ./recipes/*.md").read().split("\n") ])
    count_id = set([])
    count_url = set([])
    file = pd.read_excel("allrecipes.xlsx")
    print(file.shape)
    #token = get_access_token()
    #for i in range(66705,40551,-1): count_url.add(file.iloc[i]['URL'])
    for i in [ int(line.split(".")[0]) for line in open("zero.txt","r") ]:
    #for i in range(4000,2000,-1):
        url = file.iloc[i]['URL']
        name = file.iloc[i]['菜名']
        theme = file.iloc[i]['分类']
        if url not in count_url:
        #if url in candidate and url not in count_url and str(i) not in count_id: 
            count_url.add(url)
            #ret = main(i,theme,name,token)
            ret = main_google(i,name)
            repeat = 0
            while ret == False and repeat < 5:
                repeat += 1
                time.sleep(3) 
                #ret = main(i,theme,name,token)
                ret = main_google(i,name)
            time.sleep(3) 
